import base64
from flask import request, render_template, jsonify, current_app, Blueprint, session

from models import db
from models.user import User
from service.authtoken import create_token

login_route = Blueprint('login', __name__)


@login_route.route("/login", methods=["GET", "POST"])
def login_view():
    if request.method == "GET":
        return render_template("login.html")
    elif request.method == "POST":
        request_data = request.get_json()
        if request_data is None:
            return jsonify(code=3, msg="未接收到参数")

        username = request_data.get("username")
        password = base64.b64decode(request_data.get("password")).decode('utf-8')

        user_obj = User.query.filter(User.username == username).first()

        if not user_obj:
            return jsonify(code=3, msg="用户名不存在")

        if not user_obj.validate_password(password):
            return jsonify(code=2, msg="密码错误")

        token = create_token({"user_id": user_obj.id}, current_app.config["SECRET_KEY"])
        try:
            user_obj.token = token
            db.session.commit()
            session["token"] = token
            return jsonify(code=0, msg="登录成功", token=token)
        except Exception:
            db.session.rollback()
            return jsonify(code=1, msg='登录失败')
